import { Button, CountDown, Toast } from 'esy-ui';
import { useCallback, useState } from 'react';
import { useFormatText } from '@/hooks';
import { postSendVerfiyCode } from '@/services';

function SendCode({ form, conKey }: any) {
  const { text } = useFormatText();
  const [time, setTime] = useState(null);

  // 发送验证码
  const onSend = useCallback(() => {
    const BindInfo = form.getFieldValue('BindInfo');
    let Type = null;
    let SendType = 1;
    // 资金密码修改
    if (conKey === 'editFundPwd') {
      SendType = 4;
      Type = form.getFieldValue('Type') === '2' ? 2 : 3;
    } else if (conKey === 'bindMobile') {
      Type = 2;
    } else if (conKey === 'bindEmail') {
      Type = 3;
    }
    if (!BindInfo) {
      Toast.show({ content: text('text_88') });
    } else {
      postSendVerfiyCode({ BindInfo, Type, SendType })
        .then(() => {
          setTime(59);
        })
        .catch(() => {});
    }
  }, [conKey, form, text]);

  // 倒计时结束时修改time
  const onEnd = useCallback(() => {
    setTime(null);
  }, []);

  if (typeof time === 'number') {
    return <CountDown classNames={{ box: 'w-24 ml-2 bg-color-19 rounded py-1 text-center' }} onEnd={onEnd} time={time} format={{ sec: 's' }} type='ss' />;
  }

  return (
    <Button classNames={{ 'box:default': 'rounded font-bold bg-color-21 text-white ml-2' }} onClick={onSend}>
      {text('text_121')}
    </Button>
  );
}

export default SendCode;
